package com.yh.netty.c1.test;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author MtRider
 * @version 1.0
 * @description 卖票练习
 * @GiteeAndGithub MtRider
 * @date 2022/3/16 15:19
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
    public static void main(String[] args) throws InterruptedException {
        TicketWindow window = new TicketWindow(1000);

        //所有线程的集合
        List<Thread> threadList = new ArrayList<>();
        //卖出的票数统计
        List<Object> amountList = new Vector<>();
        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                int amount = window.sell(randAmout());
                try {
                    Thread.sleep(randAmout());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }
        for (Thread thread : threadList) {
            thread.join();
        }

        //统计卖出的票数和剩余的票数
        log.debug("余票:{}", window.getCount());
        log.debug("卖出的票:{}", amountList.stream().mapToInt(i -> (int) i).sum());

    }

    //random线程安全
    static Random random = new Random();

    //随机1~5
    public static int randAmout() {
        return random.nextInt(5) + 1;
    }
}

@Slf4j(topic = "c.TicketWindow")
class TicketWindow {
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}
